/*
 * @Author: yanjikun
 * @Date: 2021-12-31 14:50:58
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-06-08 11:58:40
 * @Description: file content
 */
import { message } from 'ant-design-vue'
import { ref } from 'vue'
interface CustomRequestOption {
  message?: string
}

/**
 * @description:
 * @param {*} axios 请求函数
 * @param {*} callback 请求成功的回调
 * @param {*} options 配置项
 * @param {*} errorBack 请求错误的回调
 * @author: yanjikun
 */
export const useRequest = <T = any>(
  axios: Promise<T>,
  callback: (res: T) => void,
  options?: CustomRequestOption,
  errorBack?: (error: any) => void,
) => {
  const loading = ref(false)
  const content = ref<T>()
  const { message: messageContent } = options ?? {}
  loading.value = true
  axios
    .then((result) => {
      content.value = result
      message.success(messageContent ?? '操作成功！')
      callback(result)
    })
    .catch((err) => {
      errorBack?.(err)
    })
    .finally(() => {
      loading.value = false
    })
  return {
    loading,
    content,
  }
}
